/**
 * 封装网络请求
 */

import indexConfig from '@/config/index.config'
import $store from '@/store/index.js'

module.exports = (params) => {
	let url = '',
		useConfig, data = {
			// client: 'mp-weixin',
			// need_user_info: true
		};
	url = indexConfig.baseUrl + params.url; // 线上环境中开启
	// url = "/dpc" + params.url; // 本地访问时开启
	let method = params.method || 'get';
	let header = params.header || {};
	data = (params.data && Object.keys(params.data).length !== 0 ? {
		...params.data,
		...data
	} : '') || data;
	uni.getSystemInfo({
		success: res => {
			useConfig = res;
		}
	})
	// 请求方式 get post
	if (method) {
		method = method.toUpperCase(); // 小写转大写
		if (method == "POST" || "GET") {
			header = {
				'content-type': 'application/json;charset=utf8',
				'Authorization': $store.state.userInfo.token || (uni.getStorageSync('userInfo').token || '')
			};
		}
	}
	//	发起请求 加载动画
	if (!params.hideLoading) {
		// uni.showNavigationBarLoading()
	}

	//	发起网络请求
	uni.request({
		url: url,
		data: data,
		dataType: 'json', // 'json' : 'sting'
		sslVerify: false,
		method: method || "GET",
		header: header,
		success: res => {
			if (res.statusCode && res.statusCode != 200) {
				//	api错误
				uni.showModal({
					content: '网络错误, 请稍后再试~'
				})
				return;
			}
			typeof params.success == "function" && params.success(res.data);
		},
		fail: err => {
			console.log(err)
			uni.showModal({
				content: '加载失败, 稍后再试~'
			})
			typeof params.fail == "function" && params.fail(err.data);
		},
		complete: (e) => {
			if (e.data.code !== 1) {
				uni.showToast({
					title: e.data.msg,
					icon: 'none',
					mask: true
				})
				if (e.data.code === 30202 || e.data.code === 30203 || e.data.code === 30204 || e.data.code === 401) {
					uni.removeStorage({
						key: 'userInfo'
					})
					uni.removeStorage({
						key: 'authLogin'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/packageA/pages/authLogin/index'
						})
					}, 500)
				}
				return
			}
			typeof params.complete == "function" && params.complete(e.data);
			return;
		}
	})
}